package com.code.refactoring.zookeeper.book.chapter05.java客户端操作.分布式锁.demo1;

import org.apache.zookeeper.ZooKeeper;

/**
 * @author wangxi created on 2023/10/15 23:49
 * @version v1.0
 *
 *  https://zhuanlan.zhihu.com/p/363323742
 *
 *  https://cloud.tencent.com/developer/article/2060617
 *
 */
public class ZkLockTest {
    public static void main(String[] args)throws Exception {
        ZooKeeper zooKeeper = ZKUtils.getZooKeeper();
        //模拟多线程请求
        for (int i = 0; i < 5; i++) {
            String threadName = "LockThread-"+i;
            new Thread(()->{
                ZKLockUtils lockUtils = new ZKLockUtils();
                lockUtils.setZooKeeper(zooKeeper);
                lockUtils.setThreadName(threadName);
                //加锁
                lockUtils.lock();
                System.out.println(Thread.currentThread().getName()+"正在执行任务");
                //模拟执行任务
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //解锁
                lockUtils.ulock();
            },threadName).start();
        }
    }
}
